import axios from "axios";
import {ElLoading, ElMessage} from "element-plus";
import store from "@/store";
import uInfo from "@/store/state/userinfo.state";
let loadingObj = null;
//使用create创建axios实例
const Service = axios.create({
    timeout: 8000,
    baseURL: "http://localhost:8080",
    headers: {
        "content-type": "application/json;charset=utf-8",
        "Authorization": store.state.uInfo.userInfo.token
    }
})
//请求拦截，请求之前
Service.interceptors.request.use(config => {
    loadingObj = ElLoading.service({
        lock: true,
        text: "Loading",
        background: "rgba(0,0,0,0.7)"
    });
    return config;
});
//响应拦截。读取到数据后。读取默认错误数据的异常处理。
Service.interceptors.response.use(response => {
    loadingObj.close();
    let data = response.data;
    if (data.code!==200){
        ElMessage.error(data.msg || "服务器错误，请联系技术管理员！")
    }
    return data;
}, error => {
    loadingObj.close();
    ElMessage({
        message: "服务器错误：" + error.error,
        type: "error",
        duration: 2000
    });
});

// post请求
export const post = config => {
    return Service({
        ...config,
        method: 'post',
        data: config.data
    });
}
// get请求
export const get = config => {
    return Service({
        ...config,
        method: 'get',
        params: config.data
    });
}